import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout/index.vue'
import Login from '../views/Login/index.vue'
import Home from '../views/Home/index.vue'

const Goods=()=>import('../views/Goods/Goods.vue')
const Params=()=>import('../views/Params/Params.vue')
const Advert=()=>import('../views/Advert/Advert.vue')
const Order=()=>import('../views/Order/index.vue')
const OrderList=()=>import('../views/Order/OrderList/index.vue')
const OrderBack=()=>import('../views/Order/OrderBack/index.vue')

const AddGoods=()=>import('../views/Goods/AddGoods.vue')

import { backtopEmits } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Layout,
      // 路由元信息
      meta: { requiresAuth: true },
      children:[
        {
          path:'/',
          name:'Home',
          component:Home
        },{
          path:'/goods',
          name:'Goods',
          component:Goods
        },{
          path:'/add-goods',
          name:'AddGoods',
          component:AddGoods
        },{
          path:'/params',
          name:'Params',
          component:Params
        },{
          path:'/advert',
          name:'Advert',
          component:Advert
        },{
          path:'/order',
          name:'Order',
          component:Order,
          redirect:'/order/order-list',
          children:[
            {
              path:'order-list',
              component:OrderList,
            },{
              path:'order-back',
              component:OrderBack,
            }
          ]
        },
      ]
    },
    {
      path: '/login',
      name: 'Login',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/Login/index.vue')
    }
  ]
})

// router.beforeEach((to,from,next)=>{
//   console.log('---to---',to);
//   // 判断是否需要登录
//   if (to.matched.some(ele=>ele.mata.isLogin)) { 
//     // 判断当前用户是否已经登录
//     let token='';
//     if (token) {
//       next()
//     } else {
//       next('/login')
//     }
//   } else {//不需要登陆
//     next();
//   }
// })

router.beforeEach((to, from) => {
  // 而不是去检查每条路由记录
  // to.matched.some(record => record.meta.requiresAuth)
  let token='';
  if (localStorage.getItem('admin')) {
    token='admin'
    // location.href('http://127.0.0.1:5173/')
  };
  if (to.meta.requiresAuth && !token) {
    // 此路由需要授权，请检查是否已登录
    // 如果没有，则重定向到登录页面
    return {
      path: '/login',
      // 保存我们所在的位置，以便以后再来
      query: { redirect: to.fullPath },
    }
  }
})



export default router

















